﻿package screen;

import java.util.Vector;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import main.GameCanvas;
import main.NuoiThuMidlet;
import model.Animal;
import model.Command;
import model.DataManager;
import model.IAction;
import model.Position;
import network.Session;
import service.GlobalService;
import utilities.CRes;
import utilities.GameResource;
import utilities.TField;
import utilities.TileMap;
import font.BitmapFont;

public class LoginScr extends Screen{
    
    public static String m_strVersionInfo;
    public static String m_strLinkVersion;
    public static boolean m_bHasNewVersion = false;
    
    public TField tfUser;
    public TField tfPass;
    public TField tfRegPass;
    
    int focus;
    int xC;
    int defYL;
    boolean isCheck = false, isRes = false, isChangePass = false;
    Command cmdLogin, cmdCheck, cmdRes, cmdChangePass;
    public Image m_imgBackground;
    
    int g = 0;
    int ylogo = -40;
    int dir = 1;
    int yKitty = 0;

    public Animal m_dog,m_newdog;
    //show login screen
    public void switchToMe() {
        resetLogo();
        resetTF();
        super.switchToMe();
    }

    //exit game
    public void close() {
        NuoiThuMidlet.instance.notifyDestroyed();
    }

    public LoginScr() {    	
    	TileMap.instance.loadMap(TileMap.LOGIN_MAP);
        
        //draw background to image buffer
        int height = GameResource.instance.imgScreenLogin.getHeight()+TileMap.m_iHeightTile*3;
        m_imgBackground = Image.createImage(GameCanvas.w, height);
 
        Graphics g = m_imgBackground.getGraphics();
        g.setColor(0x8be2ff);
        g.fillRect(0, 0, GameCanvas.w, GameCanvas.h);
        int i = 0;
        int tmpW = GameResource.instance.imgScreenLogin.getWidth();
        for(i = 0; i < GameCanvas.w; i += tmpW){
        	g.drawImage(GameResource.instance.imgScreenLogin, i, 20, Graphics.LEFT | Graphics.TOP);
        }        
        TileMap.instance.paintMap(g, 0, GameResource.instance.imgScreenLogin.getHeight());
        int wMap = TileMap.instance.m_gardenMap.m_iMapWidth * TileMap.m_iWidthTile;
        if(wMap < GameCanvas.w){
        	//adding tile for large screen
        	tmpW = (GameCanvas.w - wMap)/TileMap.m_iWidthTile + 1;
        	TileMap.instance.paintMap(g, wMap, GameResource.instance.imgScreenLogin.getHeight(), tmpW, TileMap.instance.m_gardenMap.m_iMapHeight);
        }
        
        g.drawImage(GameResource.instance.imgTree, GameCanvas.hw +50, GameResource.instance.imgScreenLogin.getHeight() - 38, Graphics.LEFT | Graphics.TOP);
        g.drawImage(GameResource.instance.imgTree, GameCanvas.hw - 80, GameResource.instance.imgScreenLogin.getHeight() - 35, Graphics.LEFT | Graphics.TOP);
                
        int tmp = GameCanvas.w/3;
        tmpW = GameResource.instance.imgFance.getWidth();
        for(i = 0; i < tmp; i += tmpW){
        	g.drawImage(GameResource.instance.imgFance, i, GameResource.instance.imgScreenLogin.getHeight() - 10, Graphics.LEFT | Graphics.TOP);
        }
        tmp = GameCanvas.w2d3;
        for(i = GameCanvas.w; i > tmp; i -= tmpW){
        	g.drawImage(GameResource.instance.imgFance, i, GameResource.instance.imgScreenLogin.getHeight() - 10, Graphics.RIGHT | Graphics.TOP);
        }
        
        defYL = GameCanvas.hh - 100;
        resetLogo();
        ///////////animal
    	m_dog = new Animal(6);
    	m_newdog = new Animal(6);
    	m_newdog.m_iLeft = m_dog.m_iLeft = 0;
    	m_newdog.m_iTop = m_dog.m_iTop = GameCanvas.h - GameResource.instance.imgScreenLogin.getHeight()/2 - GameCanvas.hBottomBar -16;
    	
    	m_newdog.m_iBoundW = m_dog.m_iBoundW = GameCanvas.w - 23;
    	m_newdog.m_iBoundH = m_dog.m_iBoundH = GameCanvas.h - GameCanvas.hBottomBar - m_newdog.m_iTop -16 ;
    	
    	m_dog.start(new Position(50, 50));       
        m_newdog.start(new Position(100, 100));
    
        int wC = GameCanvas.w - 30;
        if (wC < 70) {
            wC = 70;
        }
        if (wC > 99) {
            wC = 99;
        }

        System.out.println("game canvas w " + GameCanvas.w + " h " + GameCanvas.h);
        xC = ((GameCanvas.w - wC) >> 1) + 30;
        if (GameCanvas.w <= 180) {
            wC = 80;
            xC = ((GameCanvas.w - wC) >> 1) + 5;
        }

        //init text field user
        tfUser = new TField();
        tfUser.y = GameCanvas.hh - ITEM_HEIGHT - 40;
        tfUser.width = wC - 15;
        tfUser.height = ITEM_HEIGHT + 2;
        tfUser.isFocus = true;
        tfUser.setIputType(TField.INPUT_ALPHA_NUMBER_ONLY);
        TField.m = NuoiThuMidlet.instance;
        TField.c = GameCanvas.instance;

        //init text field pass
        tfPass = new TField();
        tfPass.y = GameCanvas.hh - 35;
        tfPass.width = wC - 15;
        tfPass.height = ITEM_HEIGHT + 2;
        tfPass.isFocus = false;
        tfPass.setIputType(TField.INPUT_TYPE_PASSWORD);

        //init text field register
        tfRegPass = new TField();
        tfRegPass.y = GameCanvas.hh - 5;
        tfRegPass.width = wC - 15;
        tfRegPass.height = ITEM_HEIGHT + 2;
        tfRegPass.isFocus = false;
        tfRegPass.setIputType(TField.INPUT_TYPE_PASSWORD);

        //save status
        int a = CRes.loadRMSInt("oncheck");
        if (a == 0) {
            isCheck = true;
        } else {
            isCheck = false;
        }

        //load username and pass
        tfUser.setText(CRes.loadRMSString("onac"));
        tfPass.setText(CRes.loadRMSString("onpass"));
        resetTF();

        focus = 0;

        cmdLogin = new Command(GameResource.signIn, new IAction() {

            public void perform() {
                doLogin();
            }
        });

        cmdCheck = new Command(GameResource.remember, new IAction() {

            public void perform() {
                if (isCheck) {
                    isCheck = false;
                } else {
                    isCheck = true;
                }
            }
        });

        m_cmdLeft = new Command(GameResource.menu, new IAction() {

            public void perform() {
                doMenu();
            }
        });

        cmdRes = new Command(GameResource.register, new IAction() {

            public void perform() {
                doRegister();
            }
        });
        cmdChangePass = new Command(GameResource.forgetPass, new IAction() {

            public void perform() {
                // TODO Auto-generated method stub
                doChangePass();
            }
        });

        m_cmdCenter = cmdLogin;
        m_cmdRight = tfUser.cmdClear;

     //  System.gc();
    }
	
    public void keyPress(int keyCode) {
        if (tfUser.isFocus) {
            tfUser.keyPressed(keyCode);
        } else if (tfPass.isFocus) {
            tfPass.keyPressed(keyCode);
        } else if (isRes && tfRegPass.isFocus) {
            tfRegPass.keyPressed(keyCode);
        }
        super.keyPress(keyCode);
    }
    
    //do change password
    private void doChangePass() {
        if (tfUser.getText().equals("")) {
            GameCanvas.startOKDlg(GameResource.plzInputInfo);
            return;
        }

      //send to server
        
        GameCanvas.startOK("Chỉ có thể lấy lại mật khẩu bằng SĐT đã đăng ký", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				GameCanvas.startWaitDlg(GameResource.plzWait);
				
				Session.gI().connect(NuoiThuMidlet.IP, NuoiThuMidlet.PORT);
		        GlobalService.gI().doRequestForgetPass(NuoiThuMidlet.PROVIDER_ID, tfUser.getText());		      
			}
		}); 
    }

    //do register new account
    protected void doRegister() {
        if (tfUser.getText().equals("") || tfPass.getText().equals("") || tfRegPass.getText().equals("")) {
            GameCanvas.startOKDlg(GameResource.plzInputInfo);
            return;
        }
        char[] ch = tfUser.getText().toCharArray();
        int a = ch.length;
        for (int i = 0; i < a; i++) {
            if (!TField.setNormal(ch[i])) {
                GameCanvas.startOKDlg(GameResource.specialCharNotAllow);
                return;
            }
        }

        if (!tfPass.getText().equals(tfRegPass.getText())) {
            GameCanvas.startOKDlg(GameResource.incorrectPass);
            return;
        }

        ////send to server
        
        Session.gI().connect(NuoiThuMidlet.IP, NuoiThuMidlet.PORT);
        GlobalService.gI().doRegister(NuoiThuMidlet.PROVIDER_ID, tfUser.getText(), tfPass.getText());
    }

    public void doBackLoginScreen() {
        //return login screen
        isRes = false;
        tfRegPass.isFocus = false;
        tfPass.isFocus = false;
        tfUser.isFocus = true;
        m_cmdRight = tfUser.cmdClear;
        resetTF();
    }

    //show menu
    protected void doMenu() {
        Vector menu = new Vector();
        if (isRes || isChangePass) {
            menu.addElement(new Command(GameResource.signIn, new IAction() {

                public void perform() {
                    isRes = false;
                    isChangePass = false;

                    tfRegPass.isFocus = false;
                    tfPass.isFocus = false;
                    tfUser.isFocus = true;
                    m_cmdRight = tfUser.cmdClear;

                    if (tfUser.y > tfPass.y) {
                        int tmp = tfPass.y;
                        tfPass.y = tfUser.y;
                        tfUser.y = tmp;
                    }
                    resetTF();
                }
            }));
        } else {
            menu.addElement(new Command(GameResource.register, new IAction() {

                public void perform() {
                	
                    isRes = true;
                    isChangePass = false;

                    tfRegPass.isFocus = false;
                    tfPass.isFocus = false;
                    tfUser.isFocus = true;
                    m_cmdRight = tfUser.cmdClear;

                    if (tfUser.y > tfPass.y) {
                        int tmp = tfPass.y;
                        tfPass.y = tfUser.y;
                        tfUser.y = tmp;
                    }

                    resetTF();
                }
            }));

            menu.addElement(new Command(GameResource.forgetPass, new IAction() {

                public void perform() {
                	isChangePass = true;
                    tfRegPass.isFocus = false;
                    tfPass.isFocus = false;
                    tfUser.isFocus = true;
                    m_cmdRight = tfUser.cmdClear;

                    if (tfUser.y < tfPass.y) {
                        int tmp = tfPass.y;
                        tfPass.y = tfUser.y;
                        tfUser.y = tmp;
                    }

                    resetTF();

                }
            }));

            menu.addElement(new Command(GameResource.forum, new IAction() {

                public void perform() {
                    GameCanvas.startOKDlg(GameResource.doYouWantGoToForum, new IAction() {

                        public void perform() {
                            try {
                                GameCanvas.endDlg();
                                String url = "http://m.taigamejava.com/";
                                NuoiThuMidlet.instance.platformRequest(url);
                                close();
                                NuoiThuMidlet.instance.notifyDestroyed();
                            } catch (ConnectionNotFoundException e) {
                                e.printStackTrace();
                            }

                        }
                    });
                }
            }));

            menu.addElement(new Command(GameResource.update, new IAction() {
                public void perform() {
                    GameCanvas.startOKDlg(GameResource.doYouWantGoToUpdate, new IAction() {

                        public void perform() {
                        	
                            try {
                                GameCanvas.endDlg();
                                String url = "http://myzone.vn/app/sk/up.jsp";
                                NuoiThuMidlet.instance.platformRequest(url);
                                close();
                                NuoiThuMidlet.instance.notifyDestroyed();
                            } catch (ConnectionNotFoundException e) {
                                e.printStackTrace();
                            }                        	 
                        }
                    });
                }
            }));

            menu.addElement(new Command(GameResource.cleanCache, new IAction() {

                public void perform() {
                    DataManager.gI().cleanDataCache();
                }
            }));
            menu.addElement(new Command(GameResource.introduction, new IAction() {

                public void perform() {
                    GameCanvas.startOKDlg("MyZoo \n Version 1.0.0 \n Bản quyền thuộc công ty CP truyền thông HDC Việt Nam \n SCKH : 0422425649");

                }
            }));


        }
        
        menu.addElement(new Command(GameResource.exit, new IAction() {

            public void perform() {
                GameCanvas.startOKDlg(GameResource.doYouWantExit, new IAction() {

                    public void perform() {
                        close();
                    }
                });
            }
        }));

        //assign to menu
        GameCanvas.menu.startAt(menu, 0);
    }

    //do login to game
    protected void doLogin() {
        //check user input
        if (tfUser.getText().length() == 0 || tfPass.getText().length() == 0) {
            GameCanvas.startOKDlg(GameResource.plzInputInfo);
            return;
        }
        
        //show waiting dialog
        GameCanvas.startWaitDlg(GameResource.plzWait);

        //connect to server
        Session.gI().connect(NuoiThuMidlet.IP, NuoiThuMidlet.PORT);


        GlobalService.gI().login(tfUser.getText(), tfPass.getText(), NuoiThuMidlet.version);
        if (m_bHasNewVersion) {
            GameCanvas.startOKDlg(m_strVersionInfo, new IAction() {

                public void perform() {
                    // TODO Auto-generated method stub
                    try {
                        GameCanvas.endDlg();
                        NuoiThuMidlet.instance.platformRequest(m_strLinkVersion);
                        NuoiThuMidlet.instance.notifyDestroyed();
                    } catch (ConnectionNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            m_bHasNewVersion = false;
        }

        //save pass
        savePass();
    }

    public void update() {
    	m_newdog.update();
    	m_dog.update();
    	
        //update animation for text field
        if (tfUser.x != xC) {
            tfUser.x += (xC - tfUser.x + 1) >> 1;
        }

        if (tfPass.x != xC) {
            tfPass.x += (xC - tfPass.x) >> 1;
        }

        if (tfRegPass.x != xC) {
            tfRegPass.x += (xC - tfRegPass.x + 1) >> 1;
        }

        tfUser.update();
        tfPass.update();

        if (isRes) {
            tfRegPass.update();
        }

        //update animation jumping for logo
        updateLogo();

        //assign center command 
        if (isChangePass) {
            m_cmdCenter = cmdChangePass;
        } else if (isRes) {
            m_cmdCenter = cmdRes;
        } else if (focus == 2) {
            m_cmdCenter = cmdCheck;
            if (isCheck) {
                m_cmdCenter.caption = GameResource.no;
            } else {
                m_cmdCenter.caption = GameResource.remember;
            }
        } else {
            m_cmdCenter = cmdLogin;
        }

        //calculate y of logo
        if (g >= 0) {
            ylogo += dir * g;
            g += dir * 2;
            if (g <= 0) {
                dir *= -1;
            }
            if (ylogo > 0) {
                dir *= -1;
                g -= 4;
            }
        }
    }

    public void updateLogo() {
        if (defYL != yL) {
            yL += (defYL - yL) >> 1;
        }
        if(yKitty < 17){
        	yKitty += 3 ;
        }
    }
    
    public void paint(Graphics g) {
        g.setColor(0x8be2ff);
    	g.fillRect(0, 0, GameCanvas.w, GameCanvas.h);
    	
        //draw background        
        g.drawImage(m_imgBackground, 0, GameCanvas.h - m_imgBackground.getHeight() - GameCanvas.hBottomBar, 0);
       
        int xBox = tfUser.x - 70;
        if (GameCanvas.w <= 200) {
            xBox = tfUser.x - 50;
        }
        //////paint dog
        //paint Animal
        if(m_newdog.m_position.y < m_dog.m_position.y){
	        m_newdog.paintDog(g);
	        m_dog.paintDog(g);
        }
        else{
        	m_dog.paintDog(g);
        	m_newdog.paintDog(g);	        
        }
        
        //paint kitty
        PaintPopup.paintKitty(g, GameCanvas.hw - GameResource.instance.imgLogo.getWidth()/2 + 26, defYL - yKitty);
        //paint login box
        PaintPopup.paintBox(g, xBox, defYL + 25, GameCanvas.w - (xBox << 1), 110);

        //paint logo
        PaintPopup.paintLogo(g, GameCanvas.hw + 20, yL + ylogo);
        //paint text field
       
        
        tfUser.paint(g);
        if (!isChangePass) {
            tfPass.paint(g);
        }

        if (isRes) {
            tfRegPass.paint(g);
        }
        
        //paint text for login screen
        g.setClip(0, 0, GameCanvas.w, GameCanvas.h);
        int a = 0;
        if (GameCanvas.w > 200) {
            BitmapFont.drawBoldFont(g, GameResource.username, tfUser.x - 65, tfUser.y + 4, 0xffffff, 0);
            if (!isChangePass) {
                BitmapFont.drawBoldFont(g, GameResource.password, tfPass.x - 62, tfPass.y + 4, 0xffffff, 0);
            }

            if (isRes) {
                BitmapFont.drawBoldFont(g, GameResource.nhapLai, tfRegPass.x - 62, tfRegPass.y - 3, 0xffffff, 0);
                BitmapFont.drawBoldFont(g, GameResource.password, tfRegPass.x - 62, tfRegPass.y + 11, 0xffffff, 0);
            }
            a = 10;
        } else {
            BitmapFont.drawBoldFont(g, "TK:", tfUser.x - 35, tfUser.y + 4, 0xffffff, 0);
            if (!isChangePass) {
                BitmapFont.drawBoldFont(g, "MK:", tfPass.x - 35, tfPass.y + 4, 0xffffff, 0);
            }

            if (isRes) {
                BitmapFont.drawBoldFont(g, "NL", tfRegPass.x - 35, tfRegPass.y - 3, 0xffffff, 0);
                BitmapFont.drawBoldFont(g, "MK", tfRegPass.x - 35, tfRegPass.y + 11, 0xffffff, 0);
            }
            a = 0;
        }

         if (!isRes && !isChangePass) {
           PaintPopup.drawCheckbox(g, tfUser.x - 30 + a, tfRegPass.y + 11, 11, 11, focus, isCheck);
            BitmapFont.drawBoldFont(g, GameResource.rememberInfo, tfUser.x - 15 + a, tfRegPass.y + 10, 0xffffff, 0);
        }

        BitmapFont.drawOutlinedString(g, NuoiThuMidlet.version, GameCanvas.w - 2, 2, 0xffff00, 0x000000, Graphics.TOP | Graphics.RIGHT);
        
        
        super.paint(g);
    }
    
    
    public void savePass() {
        if (isCheck) {
            CRes.saveRMSInt("oncheck", 0);
            CRes.saveRMSString("onac", GameCanvas.loginScr.tfUser.getText());
            CRes.saveRMSString("onpass", GameCanvas.loginScr.tfPass.getText());
        } else {
            CRes.saveRMSInt("oncheck", 1);
            CRes.saveRMSString("onac", "");
            CRes.saveRMSString("onpass", "");
        }
    }

    //update for key press
    public void updateKey() {
    	boolean checkFocus = false;
        if (GameCanvas.isPointerClick) {
            if (GameCanvas.isPointer(tfUser.x, tfUser.y, tfUser.width, tfUser.height)) {
                focus = 0;
                checkFocus = true;                
            } else if (GameCanvas.isPointer(tfPass.x, tfPass.y, tfPass.width, tfPass.height)) {
                focus = 1;
                checkFocus = true;
            } else if (GameCanvas.isPointer(tfRegPass.x, tfRegPass.y, tfRegPass.width, tfRegPass.height)) {
            	focus = 2;
            	if (!isRes && focus == 2) {
                    cmdCheck.action.perform();
            	}
            	checkFocus = true;
            }            
        }

        if (GameCanvas.keyPressed[2]) {
            focus--;
            if (focus < 0) {
                focus = 2;
            }
            checkFocus = true;
            GameCanvas.keyPressed[2] = false;
        } else if (GameCanvas.keyPressed[8]) {
            focus++;
            if (focus > 2) {
                focus = 0;
            }
            checkFocus = true;
            GameCanvas.keyPressed[8] = false;
        }
        
        if(checkFocus){
        	if (focus == 1) {
                tfUser.isFocus = false;
                tfPass.isFocus = true;
                tfRegPass.isFocus = false;
                m_cmdRight = tfPass.cmdClear;
            } else if (focus == 0) {
                tfUser.isFocus = true;
                tfPass.isFocus = false;
                tfRegPass.isFocus = false;
                m_cmdRight = tfUser.cmdClear;
            } else {
                tfUser.isFocus = false;
                tfPass.isFocus = false;
                if (isRes) {
                    tfRegPass.isFocus = true;
                    m_cmdRight = tfRegPass.cmdClear;
                }
            }
        }

        super.updateKey();
    }
    
    public void resetLogo() {
        yL = -50;
        yKitty = -10;
    }

    public void resetTF() {
        tfUser.x = -xC;
        tfPass.x = -xC;
        tfRegPass.x = -xC;
    }

    ///////////////////////// SERVER RESPONSE //////////////////////////////////////////////////////
    public void onSendSMS(String strData, String strSmsTo){
	   NuoiThuMidlet.sendSMS(strData, strSmsTo, new IAction() {
	
	       public void perform() {
	           // TODO Auto-generated method stub
	           GameCanvas.startOKDlg(GameResource.smsSent);
	       }
	   }, new IAction() {
	
	       public void perform() {
	           // TODO Auto-generated method stub
	           GameCanvas.startOKDlg(GameResource.sendSMSFail);
	       }
	   });
    }
}
